<?php
/**
 * User:
 * Date:
 * Time:
 */

namespace App\Common\RedisCache;


abstract class AbstractSetCache extends AbstractCache
{
    public function set($value)
    {
        $this->select();
        if (is_array($value)) {
            $r = $this::$client->sAddArray($this->key, $value);
        } else {
            $r = $this::$client->sAdd($this->key, $value);
        }

        return $r;
    }

    public function get($key = '')
    {
        $this->select();

        if (empty($key)) {
            $key = $this->key;
        }

        return $this::$client->sMembers($key);
    }

    public function len($key = ''): int
    {
        $this->select();

        if (empty($key)) {
            $key = $this->key;
        }

        return $this::$client->sCard($key);
    }

    /**
     * Set成员是否存在
     * @param string $member
     * @return bool
     */
    public function memberExists(string $member)
    {
        $this->select();

        return $this::$client->sIsMember($this->key, $member);
    }

    /**
     * 向集合中追加数据
     * @param string $value
     * @return int
     */
    public function addVal(string $value)
    {
        $this->select();

        return $this::$client->sAdd($this->key, $value);
    }


    /**
     * 获取集合的随机一个值
     * @return [type] [description]
     */
    public function randVal($limit=1){
        $this->select();
        return $this::$client->srandmember($this->key,$limit);
    }

    /**
     * 移除集合的一个或多个成员，不存在的成员将被忽略。
     * @param  string|array $members 要移除的成员，如果要移除多个请传入多个成员的数组
     * @return int   返回被移除的成员数量，不存在的成员将被忽略
     */
    public function zrem($members)
    {
        $this->select();
        $num = 0;
        if(is_array($members)){
            foreach ($members as $value) {
                $num += $this::$client->sRem($this->key, $value);
            }
        }else{
            $num += $this::$client->sRem($this->key, $members);
        }
        return $num;
    }

}
